const nodemailer = require('nodemailer')
const dotenv = require('dotenv')

dotenv.config()

const transporter = nodemailer.createTransport({
  host: 'smtp.qq.com',
  port: 465,
  secure: true,
  auth: {
    user: process.env.EMAIL_USER,
    pass: process.env.EMAIL_PASS
  }
})

const generateVerifyCode = () => {
  return Math.random().toString().slice(-6)
}

const sendVerifyCode = async (email, code) => {
  const mailOptions = {
    from: `"AI Chat" <${process.env.EMAIL_USER}>`,
    to: email,
    subject: 'AI Chat 验证码',
    html: `
      <div style="padding: 20px; background-color: #f5f5f5;">
        <h2>AI Chat 验证码</h2>
        <p>您的验证码是：<strong style="color: #1890ff; font-size: 20px;">${code}</strong></p>
        <p>验证码有效期为5分钟，请尽快完成验证。</p>
      </div>
    `
  }

  try {
    await transporter.sendMail(mailOptions)
    return true
  } catch (error) {
    console.error('发送邮件失败:', error)
    return false
  }
}

const verifyEmailConfig = async () => {
  try {
    await transporter.verify()
    console.log('邮箱配置验证成功')
    return true
  } catch (error) {
    console.error('邮箱配置验证失败:', error)
    return false
  }
}

module.exports = { generateVerifyCode, sendVerifyCode, verifyEmailConfig }
